package com.zougen202301180355.restaurant.controller;

import com.zougen202301180355.restaurant.pojo.MenuItem;
import com.zougen202301180355.restaurant.pojo.Order;
import com.zougen202301180355.restaurant.pojo.OrderDetail;
import com.zougen202301180355.restaurant.service.MenuItemsService;
import com.zougen202301180355.restaurant.service.OrderDetailsService;
import com.zougen202301180355.restaurant.service.OrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 邹根
 * 订单详情管理控制器
 */
@Controller
@RequestMapping("/orderdetails")
public class OrderDetailsController {

    @Autowired
    private OrderDetailsService orderDetailsService;

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private MenuItemsService menuItemsService;

    /**
     * 显示订单详情列表
     */
    @GetMapping("/list")
    public String list(Model model) {
        List<OrderDetail> orderDetails = orderDetailsService.getAllOrderDetails();
        model.addAttribute("orderDetails", orderDetails);
        return "orderdetails/list";
    }

    /**
     * 显示添加订单详情页面
     */
    @GetMapping("/add")
    public String showAddForm(Model model) {
        model.addAttribute("orderDetail", new OrderDetail());
        List<Order> orders = ordersService.getAllOrders();
        List<MenuItem> menuItems = menuItemsService.getAllMenuItems();
        model.addAttribute("orders", orders);
        model.addAttribute("menuItems", menuItems);
        return "orderdetails/add";
    }

    /**
     * 处理添加订单详情请求
     */
    @PostMapping("/add")
    public String addOrderDetail(@ModelAttribute OrderDetail orderDetail) {
        orderDetailsService.addOrderDetail(orderDetail);
        return "redirect:/orderdetails/list";
    }

    /**
     * 显示编辑订单详情页面
     */
    @GetMapping("/edit/{id}")
    public String showEditForm(@PathVariable("id") Integer id, Model model) {
        OrderDetail orderDetail = orderDetailsService.getOrderDetailById(id);
        model.addAttribute("orderDetail", orderDetail);
        List<Order> orders = ordersService.getAllOrders();
        List<MenuItem> menuItems = menuItemsService.getAllMenuItems();
        model.addAttribute("orders", orders);
        model.addAttribute("menuItems", menuItems);
        return "orderdetails/edit";
    }

    /**
     * 处理编辑订单详情请求
     */
    @PostMapping("/edit")
    public String editOrderDetail(@ModelAttribute OrderDetail orderDetail) {
        orderDetailsService.updateOrderDetail(orderDetail);
        return "redirect:/orderdetails/list";
    }

    /**
     * 删除订单详情
     */
    @GetMapping("/delete/{id}")
    public String deleteOrderDetail(@PathVariable("id") Integer id) {
        orderDetailsService.deleteOrderDetail(id);
        return "redirect:/orderdetails/list";
    }
}
